package www.ld.com.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import www.ld.com.common.SecurityConstants;
import www.ld.com.domain.R;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/token")
public class TokenController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @DeleteMapping("/logout")
    public R<?> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader)
    {
        String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
        JWSObject jwsObject = null;
        try {
            jwsObject = JWSObject.parse(tokenValue);
            String payload = jwsObject.getPayload().toString();
            JSONObject jsonObject = JSONUtil.parseObj(payload);
            String jti = jsonObject.getStr(SecurityConstants.JWT_JTI); // JWT唯一标识
            long exp = jsonObject.getLong(SecurityConstants.JWT_EXP); // JWT过期时间戳
            long currentTimeSeconds = System.currentTimeMillis() / 1000;
            if (exp < currentTimeSeconds) { // token已过期，无需加入黑名单
                return R.ok();
            }
            redisTemplate.opsForValue().set(SecurityConstants.TOKEN_BLACKLIST_PREFIX + jti, null, (exp - currentTimeSeconds), TimeUnit.SECONDS);
        } catch (ParseException e) {
            return R.error();
        }


        return R.ok();
    }
}
